package licode;

import java.util.ArrayList;
import java.util.Arrays;

public class L56 {
    public static int[][] merge(int[][] intervals) {
        ArrayList<int[]> ints = new ArrayList<>();
        Arrays.sort(intervals,(a,b)->{
            return a[0]-b[0];//按照第一个值进行排序
        });
        for (int i=0;i<intervals.length-1;i++){
            if (intervals[i][1]>=intervals[i+1][0]){
                //存在相交的区间,合并
                intervals[i+1][0]=intervals[i][0];//把后一个字段
                intervals[i+1][1]=Math.max(intervals[i][1],intervals[i+1][1]);
            }else {
                ints.add(new int[]{intervals[i][0],intervals[i][1]});
            }

        }
        ints.add(new int[]{intervals[intervals.length-1][0],intervals[intervals.length-1][1]});
        return ints.toArray(new int[ints.size()][]);

    }
    public static void main(String[] args) {
        int[][] intervals = {{1,3},{2,6},{8,16},{15,18}};
        int[][] merged = merge(intervals);
        for (int[] interval : merged) {
            System.out.println("[" + interval[0] + ", " + interval[1] + "]");
        }
    }

}
